package registration.adventurezone.thevine.com;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class AddChildActivity extends Activity{
	
	private EditText childFirst, childLast, dob, allergies, 
		parentFirst, parentLast, phone, churchPhone, address, city, zip, 
		guardianFirst, guardianLast;
	private Button addButton, saveButton, removeButton;
	private RadioGroup genderRadioGroup, churchPhonePrefRadioGroup;
	private RadioButton genderRadioButton, churchPhonePrefRadioButton;
	
	protected ArrayList<String> guardians;
	private ArrayAdapter<String> adapter;
	private ListView guardiansListView;
	private String selectedItem;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_child_layout);
        
        final SaveState data = (SaveState) getLastNonConfigurationInstance();
        if (data != null) {
        	//rxNum = data.rxNum;
        	//rxList = data.rxList;
            //fileName = data.fileName;
        }
        else {
	        guardians = new ArrayList<String>();
	        //fileName = "";
        }
        adapter = new ArrayAdapter<String>(this, R.layout.list_element, guardians);
        guardiansListView = (ListView) findViewById(R.id.list);
        guardiansListView.setAdapter(adapter);
        

        this.findAllViewsById();
        addButton.setOnClickListener(new OnClickListener() {           
        	public void onClick(View v) {
        		if(!guardianFirst.getText().toString().equals("") && !guardianLast.getText().toString().equals("")) {
        			adapter.add(guardianFirst.getText().toString()+" "+guardianLast.getText().toString());
        			guardianFirst.setText("");
            		guardianLast.setText("");
            		setListViewHeightBasedOnChildren();
        		}
        	}
		});
        
        saveButton.setOnClickListener(new OnClickListener() {           
        	public void onClick(View v) {
        		if(checkTextBoxValues()) {
        			
        			DBChild newChild = storeTextFields();
        			String newChildXML = XMLResourceHandler.getInstance().formatData2XML(newChild);
        			XMLResourceHandler.getInstance().writeXML2File(newChildXML);
        			resetFields();
        			//TODO : Add success dialog
        			Intent myIntent = new Intent(AddChildActivity.this, AZregActivity.class);
        			AddChildActivity.this.startActivity(myIntent);
        		}
        	}
		});
        
        removeButton.setVisibility(View.INVISIBLE);
        
        removeButton.setOnClickListener(new OnClickListener() {           
        	public void onClick(View v) {
        		adapter.remove(selectedItem);
        		removeButton.setVisibility(View.INVISIBLE);
        		selectedItem = null;
        		setListViewHeightBasedOnChildren();
        	}
		});
        
        guardiansListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
			    view.setSelected(true);
			    removeButton.setVisibility(View.VISIBLE);
			    selectedItem = adapter.getItem(position);	
			}
		});
    }
    
    private void saveLastID(int value){
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("id", value);
        editor.commit();
    }
      
    private int loadNextID(){
	    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
	    int i = (sharedPreferences.getInt("id", -1) + 1);
	    saveLastID(i);
	    return i;
    }
    
    
	private void setListViewHeightBasedOnChildren() {
        if (adapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < adapter.getCount(); i++) {
            View listItem = adapter.getView(i, null, guardiansListView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = guardiansListView.getLayoutParams();
        params.height = totalHeight + (guardiansListView.getDividerHeight() * (adapter.getCount() - 1));
        guardiansListView.setLayoutParams(params);
    }
    
    private boolean checkTextBoxValues(){

    	if(childFirst.getText().toString().equals("") || childLast.getText().toString().equals("") || dob.getText().toString().equals("") 
    			|| allergies.getText().toString().equals("") || parentFirst.getText().toString().equals("") || parentLast.getText().toString().equals("") 
    			|| phone.getText().toString().equals("") || address.getText().toString().equals("") || city.getText().toString().equals("")
    			|| zip.getText().toString().equals("")) {
    		Toast.makeText(getApplicationContext(),"Every field must have a value", Toast.LENGTH_SHORT).show();
    		return false;
    	}
    	if(adapter.getCount() == 0) {
    		Toast.makeText(getApplicationContext(),"At least one person must be authorized for Check-Out", Toast.LENGTH_SHORT).show();
    		return false;
    	}
    	if(!dob.getText().toString().matches("[0-9]{6}")) {
    		Toast.makeText(getApplicationContext(),"DOB should have 6 digits", Toast.LENGTH_SHORT).show();
    		return false;
    	}
    	if(!phone.getText().toString().matches("[0-9]{10}")) {
    		Toast.makeText(getApplicationContext(),"Phone field should have 10 digits", Toast.LENGTH_SHORT).show();
    		return false;
    	}
    	return true;
    }
    
    private void findAllViewsById() {
    	childFirst= (EditText) findViewById(R.id.childFirst);
    	childLast = (EditText) findViewById(R.id.childLast);
    	genderRadioGroup = (RadioGroup) findViewById(R.id.radioGender);
    	dob = (EditText) findViewById(R.id.dob);
    	allergies = (EditText) findViewById(R.id.allergies);
    	parentFirst = (EditText) findViewById(R.id.parentFirst);
    	parentLast = (EditText) findViewById(R.id.parentLast);
    	phone = (EditText) findViewById(R.id.phone);
    	churchPhone = (EditText) findViewById(R.id.churchPhone);
    	churchPhonePrefRadioGroup = (RadioGroup) findViewById(R.id.radioChurchPhonePref);
    	address = (EditText) findViewById(R.id.address);
    	city = (EditText) findViewById(R.id.city);
    	zip = (EditText) findViewById(R.id.zip);
    	guardianFirst = (EditText) findViewById(R.id.guardianFirst);
    	guardianLast = (EditText) findViewById(R.id.guardianLast);
    	addButton = (Button) findViewById(R.id.addButton);
    	saveButton = (Button) findViewById(R.id.saveButton);
    	removeButton = (Button) findViewById(R.id.removeButton); 
    }
    private void resetFields() {
    	childFirst.setText("");
    	childLast.setText("");
    	//genderRadioGroup
    	dob.setText("");
    	allergies.setText("");
    	parentFirst.setText("");
    	parentLast.setText("");
    	phone.setText("");
    	address.setText("");
    	city.setText("");
    	zip.setText("");
    	guardianFirst.setText("");
    	guardianLast.setText("");
    }
    
    
    private DBChild storeTextFields() {

            DBChild newChild = new DBChild();
            
            newChild.setChildFirst(childFirst.getText().toString());
            newChild.setChildLast(childLast.getText().toString());
            
            int selectedId = genderRadioGroup.getCheckedRadioButtonId();
            genderRadioButton = (RadioButton) findViewById(selectedId);
 
			newChild.setGender(genderRadioButton.getText().toString());
			newChild.setDob(new int[]{Integer.parseInt(dob.getText().toString().substring(0, 2)), 
										Integer.parseInt(dob.getText().toString().substring(2, 4)), 
										Integer.parseInt(dob.getText().toString().substring(4, 6))});
            newChild.setAllergies(allergies.getText().toString());
            newChild.setParentFirst(parentFirst.getText().toString());
            newChild.setParentLast(parentLast.getText().toString());
            newChild.setPhone(phone.getText().toString());
            newChild.setChurchPhone(churchPhone.getText().toString());
            selectedId = churchPhonePrefRadioGroup.getCheckedRadioButtonId();
            churchPhonePrefRadioButton = (RadioButton) findViewById(selectedId);
            newChild.setChurchPref(churchPhonePrefRadioButton.getText().toString());
            newChild.setAddress(address.getText().toString());
            newChild.setCity(city.getText().toString());
            newChild.setZip(zip.getText().toString());
            
            ArrayList<Guardian> guardians = new ArrayList<Guardian>();   
            
            for(int i = 0; i < adapter.getCount(); i++) {
            	String[] names = adapter.getItem(i).toString().split(" ");
                guardians.add(new Guardian(names[0], names[1]));
            }
            newChild.setGuardians(guardians);

            return newChild;
    }
    
}
